package com.design.classroommanagement.api

import com.design.classroommanagement.api.dao.AdminDao
import com.design.classroommanagement.api.dao.StudentDao
import com.design.classroommanagement.api.dao.TeacherDao
import com.design.classroommanagement.manager.UserAccountManager
import com.design.classroommanagement.manager.UserAccountManager.user
import com.design.classroommanagement.util.DBUtils
import com.laughing.lib.utils.Logs
import com.laughing.lib.utils.saveGet
import java.sql.PreparedStatement

interface Api {
    suspend fun register(
        account: String,
        pwd: String,
        role: Role
    ): Boolean?

    suspend fun login(
        account: String,
        pwd: String,
        role: Role
    ): User?

    suspend fun getUser(account: String?, role: Role): User?

    suspend fun getUserList(role: Role): List<User>?
}

object ApiManager : Api {
    override suspend fun register(account: String, pwd: String, role: Role): Boolean {
        var user = getUser(account, role)
        if (user != null) return false
        user = User(account = account, password = pwd)
        return role.getDao().add(user)
    }

    override suspend fun login(account: String, pwd: String, role: Role): User? {
        val user = getUser(account, role)
        return if (user?.password == pwd) {
            user.role = role
            UserAccountManager.saveUser(user)
            user
        } else null
    }

    override suspend fun getUser(account: String?, role: Role): User? {
        try {
            if (account == null) return null
            return role.getDao().query { put("account", account) }.saveGet(0)
        } catch (e: Exception) {
            e.printStackTrace()
            return null
        }

    }

    override suspend fun getUserList(role: Role): List<User>? {
        try {
            return role.getDao().query()
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return null
    }
}